package lv.solcraft.replication.server.rest.restlets;

import lv.solcraft.replication.server.bdb.Database;
import lv.solcraft.replication.server.dao.OperSiteDataAccess;
import lv.solcraft.replication.server.model.OperId;
import lv.solcraft.replication.server.model.OperSite;
import lv.solcraft.replication.server.model.OperState;
import lv.solcraft.replication.server.model.OperStateUpdate;
import net.sf.json.JSONNull;
import net.sf.json.JSONObject;

import org.restlet.Context;
import org.restlet.data.CharacterSet;
import org.restlet.data.Language;
import org.restlet.data.MediaType;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.resource.Representation;
import org.restlet.resource.Resource;
import org.restlet.resource.StringRepresentation;
import org.restlet.resource.Variant;

public class OperSiteResource extends Resource {

    private Database database;
    private OperId operId;
    private OperSiteDataAccess operSiteDataAccess;

    public void setDatabase(Database database) {
        this.database = database;
    }

    @Override
    public void init(Context context, Request request, Response response) {
        super.init(context, request, response);
        long siteId = Long.parseLong(request.getAttributes().get("site").toString());
        OperState operState = OperState.valueOf(request.getAttributes().get("state").toString());
        long originSiteId = Long.parseLong(request.getAttributes().get("originSiteId").toString());
        long originOperId = Long.parseLong(request.getAttributes().get("originOperId").toString());
        operId = new OperId(originSiteId, originOperId);
        operSiteDataAccess = database.getOperSiteDataAccessFactory().getInstance(siteId, operState);
        getVariants().add(new Variant(MediaType.TEXT_PLAIN));
    }

    @Override
    public boolean allowGet() {
        return true;
    }

    @Override
    public boolean allowDelete() {
        return true;
    }

    @Override
    public void handleDelete() {
        operSiteDataAccess.delete(operId);
    }

    @Override
    public Representation getRepresentation(Variant variant) {
        OperSite operSite = operSiteDataAccess.find(operId);
        if (operSite == null) {
            return new StringRepresentation(JSONNull.getInstance().toString());
        }
        JSONObject operSiteJson = OperStateUpdate.fromOperSite(operSite).toJSON();
        JSONObject operJson = operSite.getOper().toJSON(false);
        JSONObject json = new JSONObject();
        json.put("operSite", operSiteJson);
        json.put("oper", operJson);
        StringRepresentation stringRepresentation = new StringRepresentation(json.toString(2), MediaType.TEXT_PLAIN, Language.ALL, CharacterSet.UTF_8);
        return stringRepresentation;
    }
}
